package com.example.origin.demo.design.observer;

import java.util.ArrayList;
import java.util.List;

/**
 * 解决：一个对象状态改变给其他对象通知的问题
 * 关键：类中建立集合存储观察者，实现新增方法和遍历方法
 * @author zyt
 * @create 2018-05-28 18:10
 **/
public class ObserverDemo2 {
    public static void main(String[] args) {
        Transporter2 transporter = new Transporter2();

        Watcher2 police = new Police2();
        Watcher2 thief = new Thief2();

        transporter.addWatcher(thief);
        transporter.addWatcher(police);

        transporter.notifyWatchers();
    }

}

interface Watcher2 {
     void update();
}

class Police2 implements Watcher2{

    @Override
    public void update() {
        System.out.println("Police2");
    }
}

class Thief2 implements Watcher2{

    @Override
    public void update() {
        System.out.println("Thief2");
    }
}

class Transporter2 {

    List<Watcher2> list = new ArrayList<>();

    public void addWatcher(Watcher2 watcher2){
        list.add(watcher2);
    }

    public void notifyWatchers(){
        System.out.println("Transporter2 run");
        for (int i = 0; i < list.size(); i++) {
            list.get(i).update();
        }
    }

}

